"""
Ansible脚本工具
将Ansible脚本生成器集成到MCP工具系统中
"""

import json
import logging
from typing import Dict, List, Any, Optional
from datetime import datetime
import os

from .registry import register_tool
from ..features.ansible_script_generator import AnsibleScriptGenerator, ScriptPackage

logger = logging.getLogger(__name__)

# 全局Ansible脚本生成器
_script_generator: Optional[AnsibleScriptGenerator] = None

def _get_script_generator() -> AnsibleScriptGenerator:
    """获取Ansible脚本生成器实例"""
    global _script_generator
    
    if _script_generator is None:
        output_dir = os.environ.get("ANSIBLE_SCRIPT_DIR", "/tmp/ansible_scripts")
        _script_generator = AnsibleScriptGenerator(output_dir)
        logger.info("Ansible脚本生成器初始化完成")
    
    return _script_generator

async def generate_ansible_scripts_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """从Agent结果生成Ansible脚本"""
    try:
        # 获取参数
        agent_results = arguments.get("agent_results", [])
        kylin_config = arguments.get("kylin_config", {})
        target_hosts = arguments.get("target_hosts", "all")
        
        if not agent_results:
            return [{"text": "❌ 缺少Agent结果数据"}]
        
        # 获取脚本生成器
        generator = _get_script_generator()
        
        # 创建脚本包
        script_package = generator.create_script_package(
            agent_results=agent_results,
            kylin_config=kylin_config,
            target_hosts=target_hosts
        )
        
        # 转换为可序列化的格式
        package_data = {
            "package_id": script_package.package_id,
            "playbook_name": script_package.playbook.name,
            "target_hosts": script_package.playbook.hosts,
            "tasks_count": len(script_package.playbook.tasks),
            "tasks": [
                {
                    "name": task.name,
                    "action": task.action,
                    "timeout": task.timeout,
                    "retries": task.retries
                }
                for task in script_package.playbook.tasks
            ],
            "metadata": script_package.metadata,
            "created_at": script_package.created_at.isoformat()
        }
        
        logger.info(f"Ansible脚本包生成完成: {script_package.package_id}")
        return [{"text": json.dumps(package_data, ensure_ascii=False, indent=2)}]
        
    except Exception as e:
        logger.error(f"生成Ansible脚本失败: {e}")
        return [{"text": f"❌ 生成Ansible脚本失败: {str(e)}"}]

async def deploy_to_kylin_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """部署脚本到Kylin服务器"""
    try:
        # 获取参数
        package_id = arguments.get("package_id")
        kylin_server = arguments.get("kylin_server", "localhost:8080")
        kylin_credentials = arguments.get("kylin_credentials", {})
        
        if not package_id:
            return [{"text": "❌ 缺少脚本包ID"}]
        
        # 获取脚本生成器
        generator = _get_script_generator()
        
        # 查找脚本包（这里简化处理，实际应该从数据库或缓存中查找）
        # 在实际应用中，您需要实现脚本包的存储和检索机制
        
        # 模拟部署结果
        deployment_result = {
            "package_id": package_id,
            "kylin_server": kylin_server,
            "deployment_status": "success",
            "deployed_files": [
                f"/tmp/ansible_scripts/package_{package_id}_playbook.yml",
                f"/tmp/ansible_scripts/package_{package_id}_executor.py"
            ],
            "deployment_time": datetime.now().isoformat(),
            "execution_command": f"python3 /tmp/ansible_scripts/package_{package_id}_executor.py"
        }
        
        logger.info(f"脚本包已部署到Kylin: {package_id}")
        return [{"text": json.dumps(deployment_result, ensure_ascii=False, indent=2)}]
        
    except Exception as e:
        logger.error(f"部署到Kylin失败: {e}")
        return [{"text": f"❌ 部署到Kylin失败: {str(e)}"}]

async def auto_generate_and_deploy_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """自动生成脚本并部署到Kylin"""
    try:
        # 获取参数
        agent_results = arguments.get("agent_results", [])
        kylin_config = arguments.get("kylin_config", {})
        target_hosts = arguments.get("target_hosts", "all")
        kylin_server = arguments.get("kylin_server", "localhost:8080")
        kylin_credentials = arguments.get("kylin_credentials", {})
        
        if not agent_results:
            return [{"text": "❌ 缺少Agent结果数据"}]
        
        # 获取脚本生成器
        generator = _get_script_generator()
        
        # 1. 生成脚本包
        logger.info("开始生成Ansible脚本包")
        script_package = generator.create_script_package(
            agent_results=agent_results,
            kylin_config=kylin_config,
            target_hosts=target_hosts
        )
        
        # 2. 部署到Kylin
        logger.info(f"开始部署脚本包到Kylin: {script_package.package_id}")
        deployment_result = generator.deploy_to_kylin(
            script_package=script_package,
            kylin_server=kylin_server,
            kylin_credentials=kylin_credentials
        )
        
        # 3. 合并结果
        final_result = {
            "script_generation": {
                "package_id": script_package.package_id,
                "playbook_name": script_package.playbook.name,
                "tasks_count": len(script_package.playbook.tasks),
                "target_hosts": script_package.playbook.hosts
            },
            "deployment": deployment_result
        }
        
        logger.info(f"自动生成和部署完成: {script_package.package_id}")
        return [{"text": json.dumps(final_result, ensure_ascii=False, indent=2)}]
        
    except Exception as e:
        logger.error(f"自动生成和部署失败: {e}")
        return [{"text": f"❌ 自动生成和部署失败: {str(e)}"}]

async def get_script_templates_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """获取可用的脚本模板"""
    try:
        # 获取脚本生成器
        generator = _get_script_generator()
        
        # 获取任务模板
        templates = {}
        for action, template in generator.task_templates.items():
            templates[action] = {
                "name": template["name"],
                "action": template["action"],
                "description": f"执行{template['name']}的诊断任务"
            }
        
        result = {
            "available_templates": templates,
            "template_count": len(templates),
            "query_time": datetime.now().isoformat()
        }
        
        logger.info(f"获取脚本模板: {len(templates)} 个模板")
        return [{"text": json.dumps(result, ensure_ascii=False, indent=2)}]
        
    except Exception as e:
        logger.error(f"获取脚本模板失败: {e}")
        return [{"text": f"❌ 获取脚本模板失败: {str(e)}"}]

async def cleanup_old_scripts_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """清理旧的脚本文件"""
    try:
        max_age_hours = arguments.get("max_age_hours", 24)
        
        # 获取脚本生成器
        generator = _get_script_generator()
        
        # 执行清理
        generator.cleanup_old_files(max_age_hours)
        
        result = {
            "cleanup_status": "completed",
            "max_age_hours": max_age_hours,
            "cleanup_time": datetime.now().isoformat()
        }
        
        logger.info(f"清理旧脚本文件完成，最大保留时间: {max_age_hours} 小时")
        return [{"text": json.dumps(result, ensure_ascii=False, indent=2)}]
        
    except Exception as e:
        logger.error(f"清理旧脚本文件失败: {e}")
        return [{"text": f"❌ 清理旧脚本文件失败: {str(e)}"}]

# 注册工具
register_tool(
    "generate_ansible_scripts",
    "从Agent结果生成Ansible脚本包",
    {
        "type": "object",
        "properties": {
            "agent_results": {
                "type": "array",
                "description": "Agent执行结果列表",
                "items": {
                    "type": "object",
                    "properties": {
                        "agent_type": {"type": "string", "description": "Agent类型"},
                        "result": {"type": "object", "description": "执行结果"},
                        "parameters": {"type": "object", "description": "执行参数"}
                    }
                }
            },
            "kylin_config": {
                "type": "object",
                "description": "Kylin服务器配置"
            },
            "target_hosts": {
                "type": "string",
                "description": "目标主机",
                "default": "all"
            }
        },
        "required": ["agent_results"]
    },
    generate_ansible_scripts_impl
)

register_tool(
    "deploy_to_kylin",
    "部署脚本包到Kylin服务器",
    {
        "type": "object",
        "properties": {
            "package_id": {
                "type": "string",
                "description": "脚本包ID"
            },
            "kylin_server": {
                "type": "string",
                "description": "Kylin服务器地址",
                "default": "localhost:8080"
            },
            "kylin_credentials": {
                "type": "object",
                "description": "Kylin认证信息"
            }
        },
        "required": ["package_id"]
    },
    deploy_to_kylin_impl
)

register_tool(
    "auto_generate_and_deploy",
    "自动生成脚本并部署到Kylin（一站式服务）",
    {
        "type": "object",
        "properties": {
            "agent_results": {
                "type": "array",
                "description": "Agent执行结果列表",
                "items": {
                    "type": "object",
                    "properties": {
                        "agent_type": {"type": "string", "description": "Agent类型"},
                        "result": {"type": "object", "description": "执行结果"},
                        "parameters": {"type": "object", "description": "执行参数"}
                    }
                }
            },
            "kylin_config": {
                "type": "object",
                "description": "Kylin服务器配置"
            },
            "target_hosts": {
                "type": "string",
                "description": "目标主机",
                "default": "all"
            },
            "kylin_server": {
                "type": "string",
                "description": "Kylin服务器地址",
                "default": "localhost:8080"
            },
            "kylin_credentials": {
                "type": "object",
                "description": "Kylin认证信息"
            }
        },
        "required": ["agent_results"]
    },
    auto_generate_and_deploy_impl
)

register_tool(
    "get_script_templates",
    "获取可用的Ansible脚本模板",
    {
        "type": "object",
        "properties": {}
    },
    get_script_templates_impl
)

register_tool(
    "cleanup_old_scripts",
    "清理旧的脚本文件",
    {
        "type": "object",
        "properties": {
            "max_age_hours": {
                "type": "integer",
                "description": "最大保留时间（小时）",
                "default": 24
            }
        }
    },
    cleanup_old_scripts_impl
) 